﻿

using Miao.UI;
using UnityEngine;

public static partial class RectTransformExtension
{
    /// <summary>
    /// 将世界点转换为特定Screen上的点，需要注意转换到的UI中Pivot会干涉具体位置。
    /// </summary>
    /// <param name="rectTransform"></param>
    /// <param name="child"></param>
    /// <param name="worldPoint"></param>
    public static void WorldPointToScreenPoint(this RectTransform rectTransform, RectTransform child, Vector3 worldPoint)
    {
        Vector3 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main, worldPoint);
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPos, Miao.UI.UIManager.UICamera, out Vector2 uiPosition);
        child.anchoredPosition = uiPosition;
    }
    //UI转视口坐标
    public static Vector2 UIPointToScreenPoint(Vector3 uiPoint)
    {
        return RectTransformUtility.WorldToScreenPoint(UIManager.UICamera, uiPoint);
    }

    // 屏幕坐标转换为世界坐标
    public static Vector3 ScreenPointToWorldPoint(Vector2 screenPoint, float planeZ)
    {
        Vector3 position = new Vector3(screenPoint.x, screenPoint.y, planeZ);
        return Camera.main.ScreenToWorldPoint(position);
    }

    // UI坐标转换为世界坐标
    public static Vector3 UIToWorldPoint(this RectTransform uiTransform, float planeZ)
    {
        Vector3 worldPoint = uiTransform.position;
        Vector2 screenPoint = UIPointToScreenPoint(worldPoint);
        return ScreenPointToWorldPoint(screenPoint, planeZ);
    }
}

